<template>
	<div class="bank-info-form">
		<a-card title="银行信息" class="form-card">
			<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
				<a-form-item label="开户银行" name="bankName">
					<a-input v-model:value="formData.bankName" placeholder="请输入开户银行" />
				</a-form-item>
				<a-form-item label="银行卡号" name="bankAccount">
					<a-input v-model:value="formData.bankAccount" placeholder="请输入银行卡号" />
				</a-form-item>
				<a-form-item label="银行卡照片" name="bankImage">
					<a-upload
						v-model:file-list="bankImageList"
						list-type="picture-card"
						accept="image/jpeg,image/png"
						:multiple="true"
						:before-upload="beforeUpload"
						@change="handleChange"
						@preview="handlePreview"
						:showUploadList="{ showRemoveIcon: false }"
					>
						<div class="upload-btn">
							<plus-outlined />
							<div style="margin-top: 8px">上传照片</div>
						</div>
					</a-upload>
					<a-button @click="clearAllImages">清空</a-button>
					<div class="photo-count">已上传 {{ bankImageList.length }} 张照片 (需上传正反面)</div>
				</a-form-item>
			</a-form>
		</a-card>

		<a-modal v-model:open="previewVisible" :footer="null" @cancel="previewVisible = false" class="image-preview-modal">
			<img alt="预览图片" :src="previewImageSrc" style="width: 100%" />
		</a-modal>
	</div>
</template>

<script setup>
	import { ref, watch } from 'vue'
	import { message } from 'ant-design-vue'
	import onboardingRegistryApi from '@/api/hrms/onboarding/registry/onboardingRegistryApi'
	import { PlusOutlined } from '@ant-design/icons-vue'
	import Promise from 'lodash-es/_Promise'

	const props = defineProps({
		modelValue: {
			type: Object,
			required: true
		}
	})

	const formData = reactive({
		bankName: '',
		bankAccount: '',
		bankImage: ''
	})
	const formRef = ref()
	const previewVisible = ref(false)
	const previewImageSrc = ref('')
	const bankImageList = ref([])

	const jdOssBaseUrl = 'https://s3.cn-north-1.jdcloud-oss.com/'

	const formRules = {
		bankName: [{ required: true, message: '请输入开户银行', trigger: 'blur' }],
		bankAccount: [{ required: true, message: '请输入银行卡号', trigger: 'blur' }],
		bankImage: [
			{
				required: true,
				message: '请上传银行卡照片',
				validator: (rule, value) => {
					if (bankImageList.value.length === 0) {
						return Promise.reject('请上传身份证照片')
					} else {
						return Promise.resolve()
					}
				},
				trigger: 'change'
			}
		]
	}

	// 监听父组件传递的数据变化
	watch(
		() => props.modelValue,
		(newVal) => {
			Object.keys(newVal).forEach((key) => {
				if (key in formData) {
					if (key === 'bankImage' && newVal[key]) {
						const fileNames = newVal[key].split(',')
						bankImageList.value = fileNames.map((fileName, index) => ({
							uid: -index,
							name: fileName,
							status: 'done',
							url: `${jdOssBaseUrl}${fileName}`
						}))
					} else {
						formData[key] = newVal[key]
					}
				}
			})
		},
		{ immediate: true, deep: true }
	)

	const beforeUpload = (file) => {
		bankImageList.value = bankImageList.value.filter((item) => item.originFileObj)
		return false
	}

	const handleChange = ({ fileList: newFileList }) => {
		// 去重处理
		const uniqueFiles = []
		const seen = new Set()
		newFileList.forEach((file) => {
			const key = file.uid || file.name
			if (!seen.has(key)) {
				seen.add(key)
				uniqueFiles.push(file)
			}
		})
		bankImageList.value = uniqueFiles
	}

	const handlePreview = (file) => {
		previewImageSrc.value = file.url || file.thumbUrl
		previewVisible.value = true
	}

	const clearAllImages = () => {
		bankImageList.value = []
		nextTick(() => {
			formRef.value?.validateFields(['bankImage'])
		})
	}

	// 保存数据方法（供父组件调用）
	async function saveData() {
		try {
			// 验证表单
			await formRef.value.validateFields()
			const submitData = new FormData()
			submitData.append(
				'onboardingRegistryEditBo',
				new Blob(
					[
						JSON.stringify({
							bankEditBo: {
								bankName: props.modelValue.bankName,
								bankAccount: props.modelValue.bankAccount
							}
						})
					],
					{
						type: 'application/json'
					}
				)
			)
			if (bankImageList.value.length > 0) {
				bankImageList.value.forEach((file) => {
					if (file.originFileObj) {
						submitData.append('multipartFileList', file.originFileObj)
					}
				})
			}
			await onboardingRegistryApi.updateRegistryInfo(props.modelValue.id, submitData)
			message.success('银行信息保存成功')
			return true
		} catch (error) {
			console.error('表单验证失败:', error)
			message.error('请检查表单填写是否正确')
			return false
		}
	}

	defineExpose({
		saveData
	})
</script>
<style>
	.photo-count {
		color: rgba(0, 0, 0, 0.45);
		font-size: 12px;
	}
</style>
